<!--
 * @Author: namelll 2677065112@qq.com
 * @Date: 2023-06-03 11:29:54
 * @LastEditors: namelll 2677065112@qq.com
 * @LastEditTime: 2023-06-14 14:38:38
 * @FilePath: \vue3-ts-project\src\views\login\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!--
 * @Author: namelll 2677065112@qq.com
 * @Date: 2023-06-03 11:29:54
 * @LastEditors: namelll 2677065112@qq.com
 * @LastEditTime: 2023-06-06 09:07:04
 * @FilePath: \vue3-ts-project\src\views\login\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="login_container">
    <!--col属性：xs,当屏幕宽度小于768时,进行响应式显示 -->
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :rules="rules" :model="loginForm" ref="loginForms">
          <h1>后台管理</h1>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input :prefix-icon="Lock" type="password" v-model="loginForm.password" placeholder="请输入密码"
              show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading" class="login_btn" type="primary" size="default" @click="login">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue';
import { reactive, ref } from 'vue';
//引入用户小仓库
import useUserStore from '@/store/modules/user'
//引入提供的useRouter
import { useRouter, useRoute } from 'vue-router';
import { ElNotification } from 'element-plus';
//引入获取时间函数
import { getTime } from '@/utils/time';
//获取路由器对象
let $router = useRouter();
//获取路由对象
let $route = useRoute()
//收集账号与密码的数据,reactive是响应式数据
let loginForm = reactive({
  username: 'admin', password: 'atguigu123'
})
//获取用户小仓库
let userStore = useUserStore()
//定义按钮加载状态，默认不加载
let loading = ref(false)
//获取el-form组件
let loginForms = ref();

const validatorUserName = (rule: any, value: any, callback: any) => {
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //callBack:符合条件放行通过，不符合注入错误提示信息
  if (value.length >= 5) {
    callback();
  } else {
    callback(new Error('账号长度至少5位'));
  }
}
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.length >= 6) {
    callback();
  } else {
    callback(new Error('密码长度至少6位'));
  }
}
//自定义校验规则
const rules = {
  username: [
    // blur:失去焦点；change:文本发生变化
    // { required: true, message: "用户名不能为空", trigger: "blur" },
    // { required: true, min: 6, max: 10, message: "账号至少4位", trigger: "change" }
    { trigger: 'change', validator: validatorUserName }
  ],
  password: [
    // { required: true, message: "密码不能为空", trigger: "blur" },
    // { required: true, min: 6, max: 10, message: "密码至少6位", trigger: "change" }
    { trigger: 'change', validator: validatorPassword }
  ]
}

//登录回调
const login = async () => {
  //需要保证全部表单验证之后再发请求
  // validate对整个表单的内容进行验证,接收一个回调函数，或返回 Promise。
  await loginForms.value.validate();
  loading.value = true//显示加载效果
  //点击登录之后的流程
  // 1.通知仓库发登录请求
  // 2.成功->首页；失败->错误

  try {
    //保证登录成功
    await userStore.userLogin(loginForm)
    //编程式导航跳转
    //登录时，判断路由路劲当中是否有query参数，有就向query跳转，无就向首页跳转
    let redirect: any = $route.query.redirect
    $router.push({ path: redirect || '/' });
    ElNotification({
      type: 'success',
      message: '登录成功',
      title: `Hi,${getTime()}好`
    });
    loading.value = false;
  } catch (error) {
    loading.value = false;
    ElNotification({
      type: 'error',
      message: error.message,
    })
  }
}

</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg')no-repeat;
  background-size: cover;
}

.login_form {
  position: relative;
  width: 80%;
  top: 30vh;
  background: url("@/assets/images/login_form.png") no-repeat;
  background-size: cover;
  padding: 40px;

  h1 {
    color: white;
    font-size: 30px;
    text-align: center;
    margin: 10px
  }

  .login_btn {
    width: 100%;
  }
}
</style>
